package me.numark.activities;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.model.BaseModel;
import me.numark.model.News;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;
import me.numark.view.TagItem;
import me.numark.view.TagPopup;

/**
 * Created by Evan on 15/8/2.
 */
public class MarkActivity extends BaseActivity implements View.OnClickListener, TextWatcher, TagPopup.OnItemOnClickListener {

    @Bind(R.id.right_image)
    ImageView rightImage;

    @Bind(R.id.vote_group)
    RadioGroup voteGroup;

    @Bind(R.id.link)
    EditText linkEdit;

    @Bind(R.id.mark_text)
    EditText markEdit;

    @Bind(R.id.news_title)
    EditText titleEdit;

    @Bind(R.id.link_go)
    TextView goButton;

    @Bind(R.id.add_privacy)
    Button secretButton;

    @Bind(R.id.add_tags)
    Button tagButton;

    int secret = 0;
    int tagPos = -1;

    News mNews = null;
    News wNews = null;
    public static final int REQUEST_AT_USER = 10002;
    private LinearLayout mList;
    int itemHeight;
    int onedp;
    private AlertDialog alertdialog;
    private String[] items;
    private Dialog dialog;
    private TagPopup tagPopup;
    private boolean isFromArticle;
    private String text;
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_mark;
        super.onCreate(savedInstanceState);
        titleTextView.setText(R.string.recommend);
        rightImage.setImageResource(R.drawable.action_bar_publish);
        rightImage.setVisibility(View.VISIBLE);
        rightImage.setOnClickListener(this);
        goButton.setOnClickListener(this);
        secretButton.setOnClickListener(this);
        tagButton.setOnClickListener(this);
        linkEdit.setEnabled(false);
        tagPopup = new TagPopup(this, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tagPopup.setItemOnClickListener(this);
        isFromArticle = getIntent().getBooleanExtra(Constants.FROM_ARTICLE,false);
        url = getIntent().getStringExtra(WebviewActivity.EXTRA_URL);



        try {
            String news_extra = getIntent().getStringExtra(Constants.NEWS_EXTRA);
            if (!TextUtils.isEmpty(news_extra)) {
                mNews = new Gson()
                        .fromJson(news_extra, News.class);
                if (mNews != null) {
                    titleEdit.setText(mNews.title);
                    linkEdit.setText(mNews.url);
                    titleEdit.setEnabled(false);

                }
            }
            String webvie_news_extra = getIntent().getStringExtra(WebviewActivity.EXTRA_NEWS);
            if (!TextUtils.isEmpty(webvie_news_extra)){
                wNews = new Gson()
                        .fromJson(webvie_news_extra, News.class);
                if (wNews != null){
                    titleEdit.setText(wNews.title);
                    linkEdit.setText(wNews.url);
                    titleEdit.setEnabled(false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        markEdit.addTextChangedListener(this);
        linkEdit.addTextChangedListener(watcher);
        updateSecret();
    }


    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (wNews==null) {
                if (!isFromArticle) {
                    String url = linkEdit.getText().toString().trim();
                    if (url != null) {
                        WebView webView = new WebView(MarkActivity.this);
                        webView.setWebViewClient(new WebViewClient() {
                            @Override
                            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                view.loadUrl(url);
                                return true;
                            }
                        });
                        WebChromeClient wvcc = new WebChromeClient() {
                            @Override
                            public void onReceivedTitle(WebView view, String title) {
                                super.onReceivedTitle(view, title);
                                Log.d("ANDROID_LAB", "TITLE=" + title);

                                titleEdit.setText(title);
                            }


                        };
                        webView.setWebChromeClient(wvcc);
                        webView.loadUrl(url);
                    }
                }
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        if (!isFromArticle && mNews == null) {
            /*ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            if (clipboard.hasPrimaryClip() && clipboard.getPrimaryClip().getItemCount() > 0) {
                ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
                if (item.getText() != null) {
                    text = item.getText().toString();
                    if (text != null && text.trim().startsWith("http")) {
                        linkEdit.setText(text);
                    }

                }
            }*/
            if (url != null && url.trim().startsWith("http")){
                linkEdit.setText(url);
            }
        }
    }

    void updateSecret() {
        switch (secret) {
            case 0:
            default:
                secretButton.setText(R.string.secret_0);
                break;
            case 1:
                secretButton.setText(R.string.secret_1);
                break;
            case 2:
                secretButton.setText(R.string.secret_2);
                break;
        }
    }

    void showSecretDialog() {
        /*final AlertDialog.Builder ab = new AlertDialog.Builder(this);
        String[] items = new String[]{getString(R.string.secret_0),
                getString(R.string.secret_2),
                getString(R.string.secret_1)};
//        ab.setTitle("设置隐私状态");
        ab.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 1:
                        secret = 2;
                        break;
                    case 2:
                        secret = 1;
                        break;
                    default:
                        secret = 0;
                        break;
                }
                updateSecret();
            }
        });
        ab.setNegativeButton(android.R.string.cancel, null);
        ab.show();*/
        View view = getLayoutInflater().inflate(R.layout.choose_secret, null);
        Button btnPublic = (Button) view.findViewById(R.id.btn_public);
        Button btnOwn = (Button)view.findViewById(R.id.btn_own);
        Button btnAnonymity = (Button)view.findViewById(R.id.btn_anonymity);
        Button btnCancel = (Button)view.findViewById(R.id.btn_cancel);

        btnPublic.setOnClickListener(this);
        btnAnonymity.setOnClickListener(this);
        btnOwn.setOnClickListener(this);
        btnCancel.setOnClickListener(this);

        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    void showTagsDialog(View v) {
        tagPopup.cleanTags();
        /*alertdialog = null;
        mList = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.choose_tags,null);
        if (Global.tags == null)
            return;
        items = new String[Global.tags.length];
        for (int i = 0; i < items.length; i++) {
            items[i] = Global.tags[i].title;
        }
        buildList(Global.tags);*/

       /* final AlertDialog.Builder ab = new AlertDialog.Builder(this);
        ab.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tagPos = which;
                tagButton.setText(items[which]);
            }
        });
        if (tagPos > -1) {
            ab.setNegativeButton(R.string.delete_tag, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    tagPos = -1;
                    tagButton.setText(R.string.add_tags);
                }
            });
        }
        ab.setPositiveButton(android.R.string.cancel, null);
        ab.show();*/

        /*alertdialog = new AlertDialog.Builder(this).create();
        alertdialog.setView(mList, 0, 0, 0, 0);
        alertdialog.show();*/
        if (v.getId() == R.id.add_tags) {
            if (Global.tags==null||Global.tags.length ==0){
                Utils.showToast(getString(R.string.get_tags_error));
                return;
            }
            items = new String[Global.tags.length];
            for (int i = 0; i < items.length; i++) {
                tagPopup.addTags(new TagItem(Global.tags[i].title));
            }
            tagPopup.show(v);
        }
    }

    void publish() {
        String url = linkEdit.getText().toString().trim();
        if (url.length() == 0) {
            Utils.showSnackbar(rootView, R.string.mark_link_empty);
            return;
        }
        String title = titleEdit.getText().toString().trim();
        if (title.length() == 0) {
            Utils.showSnackbar(rootView, R.string.mark_title_empty);
            return;
        }
        String topic = markEdit.getText().toString().trim();
        final Map<String, Object> params = new HashMap<>();
        params.put("url",text);
        params.put("topic", topic);
        params.put("url", url);
        params.put("secret", String.valueOf(secret));
        params.put("title",titleEdit.getText().toString());
        if (tagPos > -1)
            params.put("label", tagButton.getText().toString());
        int star = 8;
        if (voteGroup.getCheckedRadioButtonId() == R.id.vote_bad) {
            star = 3;
        }
        params.put("star", String.valueOf(star));
        if (atList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Pair<String, String> pair : atList) {
                String name = pair.first;
                if (topic.contains("@" + name)) {
                    if (sb.length() > 0)
                        sb.append(',');
                    sb.append(pair.second);
                }
            }
            if (sb.length() > 0) {
                params.put("at_users", sb.toString());
            }
        }
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string.progress_comment)) {
            String requestUrl;
            @Override
            protected String requestServer() {
                if (wNews != null) {
                    requestUrl = String.format(NetworkConstants.MARK_PUBLISH, Global.getCurrentUid(),wNews.id);
                }else if (mNews != null){
                    requestUrl = String.format(NetworkConstants.MARK_PUBLISH,Global.getCurrentUid(),mNews.id);
                }else {
                    requestUrl = String.format(NetworkConstants.MARK_PUBLISH,Global.getCurrentUid(),0);
                }
                return HttpUtil.post(requestUrl, params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                LocalBroadcastManager.getInstance(getBaseContext())
                        .sendBroadcast(new Intent(Constants.ACTION_USER_CHANGED));
                finish();
                Utils.showToast(R.string.recommend_success);
            }
        }.setSnackbarView(rootView).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.link_go: {
                String url = linkEdit.getText().toString().trim();
                if (url.length() == 0) {
                    Utils.showSnackbar(rootView, R.string.mark_link_empty);
                    return;
                }
                Intent intent = new Intent(this, WebviewActivity.class);
                intent.putExtra(WebviewActivity.EXTRA_TITLE, getString(R.string.mark_url_preview));
                intent.putExtra(WebviewActivity.EXTRA_URL, url);
                startActivity(intent);
            }
            break;
            case R.id.add_privacy:
                showSecretDialog();
                break;
            case R.id.add_tags:
                showTagsDialog(v);
                break;
            case R.id.right_image:
                publish();
                break;
            case R.id.btn_public:
                secret = 0;
                updateSecret();
                dialog.dismiss();
                break;
            case R.id.btn_own:
                secret = 1;
                updateSecret();
                dialog.dismiss();
                break;
            case R.id.btn_anonymity:
                secret = 2;
                updateSecret();
                dialog.dismiss();
                break;
            case R.id.btn_cancel:
                dialog.dismiss();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String str = s.toString();
        String sub = str.substring(start, start + count);
        if (sub.equals("@")) {
            Intent intent = new Intent(this, ContactsActivity.class);
            startActivityForResult(intent, REQUEST_AT_USER);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case REQUEST_AT_USER: {
                String userStr = data.getStringExtra(Constants.USER_EXTRA);
                User user = Global.getGson().fromJson(userStr, User.class);
                addAt(user.nick, user.uid, false);
            }
            break;
        }
    }

    ArrayList<Pair<String, String>> atList = new ArrayList<>();

    protected void addAt(String name, int uid, boolean withAt) {
        atList.add(new Pair<>(name, String.valueOf(uid)));
        int start = Math.max(markEdit.getSelectionStart(), 0);
        int end = Math.max(markEdit.getSelectionEnd(), 0);
        if (withAt) {
            name = "@" + name;
        }
        name = name + " ";
        markEdit.getText().replace(Math.min(start, end), Math.max(start, end),
                name, 0, name.length());
        markEdit.requestFocus();
    }

    @Override
    public void onItemClick(TagItem item, int position) {
        if (items!=null){
            tagButton.setText(tagPopup.getTags(position).getTag());
        }
    }

    /*void buildList(BaseModel[] items) {

        mList.removeAllViews();
        int rows = items.length / 2;
        Context context = this;
        itemHeight = Utils.dp2px(context, 35);
        onedp = Utils.dp2px(context, 1);
        for (int i = 0; i < rows; i++) {
            LinearLayout ll = new LinearLayout(context);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            CheckBox cb1 = createCheckBox(context, items[i * 2].title, ll, i * 2);
            CheckBox cb2 = createCheckBox(context, items[i * 2 + 1].title, ll, i * 2 + 1);
            if (i == 0) {
                cb1.setBackgroundResource(R.drawable.interest_item_bg_top_left);
                cb2.setBackgroundResource(R.drawable.interest_item_bg_top_right);
            } else if (i == rows - 1) {
                cb1.setBackgroundResource(R.drawable.interest_item_bg_bottom_left);
                cb2.setBackgroundResource(R.drawable.interest_item_bg_bottom_right);
            } else {
                cb1.setBackgroundResource(R.drawable.interest_item_bg);
                cb2.setBackgroundResource(R.drawable.interest_item_bg);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mList.addView(ll, lp);
        }
    }*/

    /*CheckBox createCheckBox(Context context, final String text, LinearLayout ll, int pos) {
        CheckBox cb = new CheckBox(context);
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertdialog.dismiss();
                tagPos = 1;
                tagButton.setText(text);
            }
        });
        cb.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cb.setTextColor(context.getResources().getColorStateList(R.color.interest_item_color));
        cb.setGravity(Gravity.CENTER);
        cb.setText(text);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, itemHeight, 1);
        lp.setMargins(pos % 2 == 1 ? -onedp : 0, pos > 1 ? -onedp : 0, 0, 0);
        ll.addView(cb, lp);
        return cb;
    }*/
}
